# -*- coding: utf-8 -*-
'''
Created on 2013-5-30
socket包装类，异步接收数据
@author: 不懂d叛逆
'''
import socket, threading
import ccjhEncoder, ccjhTimer
class ccjhConnect():
	def __init__(self, NotifyFunc, Server, Port, ID, Password):
		self.__decoder = ccjhEncoder.Decoder()
		self.__sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		self.server = Server
		self.__notify = NotifyFunc
		self.port = Port
		self.IP = "127.0.0.1"
		self.__closed = True
		self.__connecting = False
		self.__thread = None
		self.ID = ID
		self.Password = Password
		self.__bReconnect = True
		return

	def __del(self):
		if self.__sock and self.__sock._closed == False:
			self.__sock.close()
			self.__sock = None
		self.__closed = True
		if self.__thread:
			self.__thread.join();
			self.__thread = None
		return

	# 关闭连接
	def Close(self, bReconnect = True):
		print("与服务器断开连接")
		if self.__sock and self.__sock._closed == False:
			self.__sock.close()
			self.__sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		self.__closed = True
		if self.__thread:
			self.__thread._stop()
			self.__thread = None
		if bReconnect == False:
			self.__bReconnect = False
		# 10秒后重连
		if self.__bReconnect and self.__connecting == False:
			ccjhTimer.onceTimer(10, self.Connect)
		return
	# 连接服务器
	def Connect(self):
		if self.__connecting:return
		print("连接服务器:%s:%d" % (self.server, self.port))
		try:
			self.__connecting = True
			self.__sock.connect((self.server, self.port))
		except:
			print("连接失败")
			self.__connecting = False
			self.Close()
			return
		self.__connecting = False
		self.__closed = False
		self.__thread = threading.Thread(target = self.ReciveFunc, args = ())
		self.__thread.start()
		self.Login()
		return

	# 发送命令
	def SendCmd(self, string):
		if self.__sock and self.__sock._closed == False:
			# print(string)
			bins = ccjhEncoder.encode(string)
			self.__sock.send(bins)
		return

	# 登录
	def Login(self):
		self.SendCmd("login %s WG2.06 %s %s  \n" % (self.IP, self.ID, self.Password))
		return

	def Loc(self, LongID):
		self.SendCmd("%d loc 0 12 12" % (LongID))
		return

	def ReciveFunc(self):
		try:
			while self.__closed == False:
				buf = self.__sock.recv(2048)
				if buf:
					bufs = self.__decoder.decode(buf)
					for b in bufs:
						self.__notify(b)
				else:
					self.Close()
					return
		except:
			self.__thread = None
		return
